<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="产品名称:" prop="materialName">
        <material-select v-model="form.materialName" @update:parameterList="handleMaterialNumberUpdate"/>
      </el-form-item>
      <el-form-item label="单据编号" prop="documentNumber">
        <el-input v-model="form.documentNumber" placeholder="请输入单据编号"/>
      </el-form-item>
      <el-form-item label="入库类型" prop="libraryType">
        <el-select clearable v-model="form.libraryType" placeholder="请选择" class="ele-fluid">
          <el-option v-for="item in libraryTypeList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入库总数">
        <el-input v-model="form.totalAmount" placeholder="请输入入库总数"/>
      </el-form-item>
      <el-form-item label="产品编号" prop="materialNumber">
        {{ parameterList.materialNumber ? parameterList.materialNumber : "--" }}
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex;justify-content: center;align-items: center" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>
<script>
import MaterialSelect from "../MaterialSelect.vue";
import {
  listProductionEceipt,
  getProductionEceipt,
  delProductionEceipt,
  addProductionEceipt,
  updateProductionEceipt
} from "@/api/InboundManagement/productionEceipt";
import {listMaterialManagement} from "@/api/basicData/materialManagement";
// // 获取当前登录状态
import {getUserProfile} from "@/api/system/user";
import {getDate} from "@/utils/getTime";
import {listStorManagement} from "@/api/basicData/storManagement";

export default {
  name: "ProductionEceipt",
  components: {
    MaterialSelect
  },
  data() {
    return {
      kuweiList: [],
      //产品编码
      materialNumber: "",
      a: 'a',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产入库管理表格数据
      productionEceiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        documentNumber: null,
        state: null,
        sourceOrderNumber: null,
        completionTime: null,
        totalAmount: null,
        createUser: null,
        lastUpdater: null,
        lastUpdateTime: null
      },
      queryParamsA: {
        pageNum: 1,
        pageSize: 20,
      },
      // 表单参数
      form: {
        custom_id: null
      },
      // 产品参数
      productForm: {
        pageNum: 1,
        materialName: '',
        pageSize: 20,
      },
      // 产品列表
      productList: [],
      // 参数
      parameterList: [],
      // 产品总页数
      totalpage: 0,
      // loading: false,
      // 表单校验
      rules: {
        documentNumber: [
          {required: true, message: "单据编号不能为空", trigger: "blur"}
        ],
        materialName: [
          {required: true, message: "请选择产品名称", trigger: "blur"}
        ],
        libraryType: [
          {required: true, message: "请选择入库类型", trigger: "blur"}
        ],
        totalAmount: [
          {required: true, message: "请选择产品名称", trigger: "blur"}
        ],
        magnitude: [
          {required: true, message: "入库总数不能为空", trigger: "blur"}
        ],
      },
      //选中的数据
      selectedRows: [],
      //入库类型
      libraryTypeList: [
        {name: "生产入库", id: 1},
        {name: "退料入库", id: 2},
        {name: "销售入库", id: 3},
        {name: "收货入库", id: 4},
        {name: "外采入库", id: 5},
      ]
    };
  },
  created() {
    this.getList();
    this.getProductlist()
    this.getUser()
    this.getKuweilist()
  },
  mounted() {
    // this.getProductlist()
    //   this.getUser()
  },
  methods: {

    // 库位列表
    getKuweilist() {
      listStorManagement().then(res => {
        //console.log('库位', res)
        this.kuweiList = res.rows
      })
    },
    //传过来的产品编码
    handleMaterialNumberUpdate(parameterList) {
      //console.log("接收到的产品编号", parameterList);
      this.parameterList = parameterList;
      // 你可以在这里将 materialNumber 传递到其他需要使用的地方
    },
    getProductlist() {
      this.loading = true;
      listMaterialManagement(this.queryParamsA).then(response => {
        this.productList = response.rows;
        this.loading = false;
      });
    },

    /** 查询生产入库管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.storageStatus = 1
      this.queryParams.zhijian = "1,2"
      this.queryParams.libraryType = 1
      listProductionEceipt(this.queryParams).then(response => {
        //console.log("出库数据555", response)
        this.productionEceiptList = response;
        this.total = response.length;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      // this.open = false;
      this.materialNumber = '';
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.ids = selection.map(item => item.deliveryId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //   handleAdd() {
    //     if (this.productList.length === 0) {
    //       Message({
    //         message: '请先添加产品',
    //         type: 'warning',
    //       });
    //     } else {
    //
    //     }
    //   },
    //   // 其他方法
    // },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.productList.length === 0) {
        this.$modal.msgSuccess({
          message: '请先添加产品',
          type: 'warning',
        });
      } else {
        this.reset();
        this.open = true;
        this.title = "添加生产入库管理";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const eceiptId = row.eceiptId || this.ids
      getProductionEceipt(eceiptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产入库管理";
      });
    },
    //            // 新增创建人
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.eceiptId != null) {
            //       // 新增创建人
            this.form.lastUpdater = this.user.userName
            this.form.lastUpdateTime = getDate()
            this.form.materialCode = this.materialNumber
            //console.log("44修改", this.form)
            updateProductionEceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.parameterList.materialNumber = '';
              this.form = {}
              // this.open = false;

              // this.getList();

            });
          } else {
            //             // 新增创建人
            this.form.creater = this.user.userName
            this.form.createUser = this.user.userName
            this.form.createTime = getDate()
            this.form.materialCode = this.parameterList.materialNumber
            this.form.materialId = this.parameterList.materialId
            this.form.storageStatus = 1
            this.form.zhijian = 1
            //console.log("444新增", this.form)
            addProductionEceipt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              //console.log("333333", this.materialNumber)
              // this.open = false;
              this.form = {}
              this.parameterList.materialNumber = '';
              // this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const eceiptIds = row.deliveryId || this.ids;
      //console.log("idsssss", this.ids, "row.deliveryId ", row.deliveryId)
      this.$modal.confirm('是否确认删除生产入库管理编号为"' + eceiptIds + '"的数据项？').then(function () {
        return delProductionEceipt(eceiptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('InboundManagement/productionEceipt/export', {
        ...this.queryParams
      }, `productionEceipt_${new Date().getTime()}.xlsx`)
    },
    //打印 ---- 合并打印
    //   handlePrint() {
    //     if (this.selectedRows.length === 0) {
    //       this.$message({
    //         message: "请选择要打印的数据",
    //         type: "warning"
    //       });
    //       return;
    //     }
    //
    //     const printWindow = window.open("", "", "width=800,height=600");
    //     printWindow.document.write("<html><head><title>打印</title></head><body>");
    //     printWindow.document.write(this.generatePrintContent());
    //     printWindow.document.write("</body></html>");
    //     printWindow.document.close();
    //     printWindow.print();
    //   },
    //   generatePrintContent() {
    //     let printContent = `
    //       <div>
    //         <h3>生产入库单</h3>
    //         <table border="1" style="width:100%; border-collapse:collapse;">
    //           <thead>
    //             <tr>
    //               <th>单据编号</th>
    //               <th>产品名称</th>
    //               <th>产品编号</th>
    //               <th>库位编号</th>
    //               <th>库区编号</th>
    //               <th>入库数量</th>
    //               <th>质检结果</th>
    //               <th>批次号</th>
    //               <th>生产日期</th>
    //               <th>有效期</th>
    //             </tr>
    //           </thead>
    //           <tbody>
    //     `;
    //
    //     this.selectedRows.forEach(row => {
    //       printContent += `
    //         <tr>
    //           <td>${row.documentNumber}</td>
    //           <td>${row.materialName}</td>
    //           <td>${row.materialCode}</td>
    //           <td>${row.materialNumber}</td>
    //           <td>${row.reservoirNumber}</td>
    //           <td>${row.totalAmount}</td>
    //           <td>${row.zhijian == 1 ? "待检" : row.zhijian == 2 ? "合格" : '不合格'}</td>
    //           <td>${row.batchNumber}</td>
    //           <td>${this.parseTime(row.productionDate, '{y}-{m}-{d}')}</td>
    //           <td>${this.parseTime(row.validity, '{y}-{m}-{d}')}</td>
    //           <td>${row.createUser}</td>
    //         </tr>
    //       `;
    //     });
    //
    //     printContent += `
    //           </tbody>
    //         </table>
    //       </div>
    //     `;
    //
    //     return printContent;
    //   },

    //打印 ---- 单独打印
    handlePrint() {
      if (this.selectedRows.length === 0) {
        this.$message({
          message: "请选择要打印的数据",
          type: "warning"
        });
        return;
      }

      const printWindow = window.open("", "", "width=800,height=600");
      printWindow.document.write("<html><head><title>打印</title></head><body>");

      // 循环生成每个表单的内容
      this.selectedRows.forEach(row => {
        printWindow.document.write(this.generatePrintContent(row));
      });

      printWindow.document.write("</body></html>");
      printWindow.document.close();
      printWindow.print();
    },

    generatePrintContent(row) {
      return `
    <div style="page-break-after: always;">
      <h3>生产入库单</h3>
      <table border="1" style="width:100%; border-collapse:collapse;">
        <thead>
          <tr>
            <th>单据编号</th>
            <th>产品名称</th>
            <th>产品编号</th>
<!--            <th>库位编号</th>-->
<!--            <th>库区编号</th>-->
            <th>入库数量</th>
            <th>质检结果</th>
            <th>批次号</th>
            <th>生产日期</th>
            <th>有效期</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>${row.documentNumber ? row.documentNumber : ' '}</td>
            <td>${row.materialName ? row.materialName : ' '}</td>
            <td>${row.materialCode ? row.materialCode : ' '}</td>
            <td>${row.materialNumber ? row.materialNumber : ' '}</td>
            <td>${row.reservoirNumber ? row.reservoirNumber : ' '}</td>
            <td>${row.totalAmount ? row.totalAmount : ' '}</td>
            <td>${row.zhijian == 1 ? "待检" : row.zhijian == 2 ? "合格" : '不合格'}</td>
            <td>${row.batchNumber}</td>
            <td>${this.parseTime(row.productionDate, '{y}-{m}-{d}')}</td>
            <td>${this.parseTime(row.validity, '{y}-{m}-{d}')}</td>
            <td>${row.createUser}</td>
          </tr>
        </tbody>
      </table>
    </div>
  `;
    }

  }
};
</script>
